package com.bryant.bryant_weather.ui.me

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ComponentCaller
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.provider.MediaStore.Images.Media
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.bryant.bryant_weather.WeatherApplication
import com.bryant.bryant_weather.base.BaseBindingActivity
import com.bryant.bryant_weather.databinding.ActChangeAvatarBinding
import com.bryant.bryant_weather.storage.TokenPreferences
import com.bryant.bryant_weather.utils.AvatarUploader
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import kotlinx.coroutines.launch


class ChangeAvatarActivity : BaseBindingActivity<ActChangeAvatarBinding>() {

    // 定义头像url - 在线地址
    private var avatarUrl: String? = null

    // 定义请求码，用于判断是拍照还是相册
    private val REQUEST_CODE_TAKE_PHOTO = 1
    private val REQUEST_CODE_PICK_PHOTO = 2
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 点击事件
        setOnClickEvent()

        // 头像回显
        // 获取存储的url
        avatarUrl = WeatherApplication.user.avatar
        loadAvatar(avatarUrl.toString())
    }

    override fun initBinding(layoutInflater: LayoutInflater): ActChangeAvatarBinding {
        return ActChangeAvatarBinding.inflate(layoutInflater)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?,
    ) {
        super.onActivityResult(requestCode, resultCode, data,)
        if (resultCode == Activity.RESULT_OK){
            when (requestCode){
                REQUEST_CODE_PICK_PHOTO -> {
                    data?.data?.let{ uri ->
                        uploadImage(uri)
//                        binding.ivAvatar.setImageURI(uri)
                    }
                }
                REQUEST_CODE_TAKE_PHOTO -> {}
            }
        }
    }


    // 1. 点击事件
    private fun setOnClickEvent() {

        // 1. 点击返回
        binding.ivBack.setOnClickListener {
            finish()
        }
        // 2. 实现点击头像或编辑头像按钮显示弹窗
        binding.ivAvatar.setOnClickListener {showPickerDialog()}
        binding.ivEditAvatar.setOnClickListener {showPickerDialog()}
    }

    // 2. 获取头像url渲染
    private fun loadAvatar(url: String) {
        lifecycleScope.launch {
            Glide.with(this@ChangeAvatarActivity)
                .load(url)
                .apply(RequestOptions.circleCropTransform())
                .into(binding.ivAvatar)
        }
    }

    // 3. 弹窗显示事件
    private fun showPickerDialog() {
        // 1. 定义数据源
        val options = arrayOf<CharSequence>("拍照", "相册", "取消")
        // 2. 创建弹窗
        val builder = AlertDialog.Builder(this)
        // 3. 设置标题
        builder.setTitle("选择头像")
        // 4. 绑定数据 - 并设置选择监听
        builder.setItems(options) {dialog, item ->
            when{
                options[item] == "拍照" -> {
                    // 拍照
                    takePhoto()
                }
                options[item] == "相册" -> {
                    // 相册
                    pickFromGallery()
                }
                options[item] == "取消" -> {
                    // 取消
                    dialog.dismiss()
                }
            }
        }
        // 5 . 显示弹窗
        builder.show()
    }

    // 4. 拍照
    private fun takePhoto() {}
    // 5. 相册
    @SuppressLint("IntentReset")
    private fun pickFromGallery() {
        // 1. 定义意图
        val intent = Intent(
            Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        )

        // 2. 设置类型
        intent.type = "image/*"

        // 3. 启动Activity
        startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO)
    }

    private fun uploadImage(uri: Uri) {
        // 开启一个协程
        lifecycleScope.launch {
            // 获取上下文
            val context = this@ChangeAvatarActivity
            val authToken = TokenPreferences.getInstance(context).getToken()
            AvatarUploader(context, authToken.toString()) { avatarUrl, error ->
                if (error != null) {
                    // 处理错误
                    Log.e("上传头像错误", error)
                } else {
                    loadAvatar(avatarUrl.toString())
                }
            }.uploadAvatar(uri)
        }
    }

}